<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';
import type { VxeGridProps } from '@vben/plugins/src/vxe-table/types';

import type { RowType } from './defaultFields.data';

import { Page, useVbenModal } from '@vben/common-ui';

import { message, Modal } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  genDefaultFieldsDelApi,
  genDefaultFieldsDeleteBatchApi,
  genDefaultFieldsQueryPageListApi,
} from '#/api/gen/defaultFields';
import { queryDictOptionsApi, useDictionaries } from '#/utils';

import DefaultFieldsFormModal from './modules/DefaultFieldsFormModal.vue';

const { translateValue } = useDictionaries([
  'yes_or_no',
  'online_table_type',
  'status',
]);

const formOptions: VbenFormProps = {
  wrapperClass: 'grid-cols-3',
  commonConfig: {
    colon: true,
    labelWidth: 80,
  },
  schema: [
    {
      component: 'ApiSelect',
      componentProps: {
        afterFetch: (data) => {
          return data.map((item: any) => ({
            label: item.itemText,
            value: Number.parseInt(item.itemVal),
          }));
        },
        api: queryDictOptionsApi,
        params: {
          dictCode: 'yes_or_no',
        },
        placeholder: '请选择是否通用',
        allowClear: true,
      },
      fieldName: 'isCommon',
      label: '是否通用',
    },
    {
      component: 'ApiSelect',
      componentProps: {
        afterFetch: (data) => {
          return data.map((item: any) => ({
            label: item.itemText,
            value: item.itemVal,
          }));
        },
        api: queryDictOptionsApi,
        params: {
          dictCode: 'online_table_type',
        },
        placeholder: '请选择表类型',
        allowClear: true,
      },
      fieldName: 'tableType',
      label: '表类型',
    },
    {
      component: 'Input',
      fieldName: 'fieldName',
      label: '字段名称',
    },
    {
      component: 'ApiSelect',
      componentProps: {
        afterFetch: (data) => {
          return data.map((item: any) => ({
            label: item.itemText,
            value: Number.parseInt(item.itemVal),
          }));
        },
        api: queryDictOptionsApi,
        params: {
          dictCode: 'status',
        },
        placeholder: '请选择状态',
        allowClear: true,
      },
      fieldName: 'status',
      label: '状态',
    },
  ],
};
const gridOptions: VxeGridProps<RowType> = {
  height: 'auto',
  toolbarConfig: {
    slots: {
      buttons: 'toolbar-buttons',
    },
  },
  columns: [
    { align: 'left', type: 'checkbox', width: 50 },
    { title: '序号', type: 'seq', width: 50 },
    {
      title: '通用字段',
      field: 'isCommon',
      cellRender: {
        name: 'CellDict',
        attrs: {
          dictCode: 'yes_or_no',
          translateValue,
        },
      },
    },
    {
      title: '表类型',
      field: 'tableType',
      cellRender: {
        name: 'CellDict',
        attrs: {
          dictCode: 'online_table_type',
          translateValue,
        },
      },
    },
    { title: '字段名称', field: 'fieldName' },
    { title: '字段注释', field: 'fieldAnnotation' },
    { title: '字段类型', field: 'fieldType' },
    { title: '字段长度', field: 'fieldLength' },
    { title: '小数点', field: 'decimalPoint' },
    {
      title: '是否主键',
      field: 'isPrimaryKey',
      cellRender: {
        name: 'CellDict',
        attrs: {
          dictCode: 'yes_or_no',
          translateValue,
        },
      },
    },
    {
      title: '允许为空',
      field: 'isNull',
      cellRender: {
        name: 'CellDict',
        attrs: {
          dictCode: 'yes_or_no',
          translateValue,
        },
      },
    },
    {
      title: '状态',
      field: 'status',
      cellRender: {
        name: 'CellDict',
        attrs: {
          dictCode: 'status',
          translateValue,
        },
      },
    },
    {
      title: '创建时间',
      field: 'createData',
      formatter: 'formatDateTime',
      width: 160,
    },
    {
      field: 'action',
      fixed: 'right',
      slots: { default: 'action' },
      title: '操作',
      width: 120,
    },
  ],
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        return await genDefaultFieldsQueryPageListApi({
          pageNo: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        });
      },
    },
  },
};
const [Grid, gridApi] = useVbenVxeGrid({ formOptions, gridOptions });
const [FromModal, formModalApi] = useVbenModal({
  connectedComponent: DefaultFieldsFormModal,
  onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      gridApi.query();
    }
  },
});

function openForm(id) {
  formModalApi.setData({
    id,
  });
  formModalApi.open();
}
async function delRow(row) {
  if (row.isHandle !== 0) {
    message.error('此项已被禁用');
    return;
  }
  const msg = await genDefaultFieldsDelApi(row.id);
  message.success(msg);
  await gridApi.query();
}
async function delBatchRow() {
  const checkboxRecords = gridApi.grid.getCheckboxRecords();
  if (checkboxRecords.length === 0) {
    message.warn('至少选中一行');
  } else {
    const idArray = checkboxRecords.map((record) => record.id);
    const ids = idArray.join(',');
    Modal.confirm({
      title: '是否删除所选中行?',
      onOk() {
        genDefaultFieldsDeleteBatchApi(ids).then(() => {
          message.success('删除成功');
          gridApi.query();
        });
      },
      class: 'test',
    });
  }
}
</script>

<template>
  <Page auto-content-height>
    <FromModal class="w-[50%]" />
    <Grid>
      <template #toolbar-buttons>
        <a-button type="primary" @click="openForm()"> 新增 </a-button>
      </template>
      <template #toolbar-tools>
        <a-button danger type="primary" @click="delBatchRow">
          批量删除
        </a-button>
      </template>
      <template #action="{ row }">
        <a-button
          :disabled="row.isHandle !== 0"
          size="small"
          type="link"
          @click="openForm(row.id)"
        >
          编辑
        </a-button>
        <a-popconfirm
          cancel-text="再想想"
          title="您确定要删除吗?"
          @confirm="delRow(row)"
        >
          <a-button
            :disabled="row.isHandle !== 0"
            size="small"
            type="link"
            danger
          >
            删除
          </a-button>
        </a-popconfirm>
      </template>
    </Grid>
  </Page>
</template>
